package grib2handler.grib.pass;

import java.io.File;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import grib2handler.grib.bean.GribBaseBean;
import grib2handler.grib.netcdf.GribPass;
import grib2handler.util.CommonUtil;
import grib2handler.util.FileUtil;
import grib2handler.util.PropertiesUtil;

public class IcePass {
	static DecimalFormat df=new DecimalFormat("#0.00");
	/**
	 * grib解压后目录
	 */
	public static final String in = GribPass.out;
	
	public static final String AVE_ICE = "aveice";
	public static final String MAX_ICE = "maxice";
	/**
	 * 发布时间
	 */
	private String time = "2014032500";
	/**
	 * 发布机构
	 */
	private String agency = "uk";
	/**
	 * 输入模块
	 */
	private String model = "cat";
	
	private String pathIn = "";
	private String pathOut = "";
	/**
	 * 基础数据存储
	 */
	private Map<String, GribBaseBean> baseDataMap = new HashMap<String, GribBaseBean>();
	/**
	 * 气压高度
	 */
	private String[] isobaric = { "300", "400", "500", "600", "700", "800" };
	
	public IcePass(String time, String agency, String model) {
		super();
		this.time = time;
		this.agency = agency;
		this.model = model;
		pathIn = in + "/" + this.time + "/"  + this.agency + "/"  + this.model;
	}
	
	/**
	 * 根据文件名设置气压高度
	 * @param fileName
	 */
	private void setIsobaric(String fileName) {
		try {
			String[] baseNameArray = CommonUtil.getTeacherList(fileName).get(0).split(",");
			//设置气压高度
			for (String string : baseNameArray) {
				if(string.contains("isobaric")) {
					GribBaseBean gb = baseDataMap.get(string.trim());
					if(gb.getItems() != null) {
						isobaric = gb.getItems();
					}
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 处理
	 * @param str
	 * @param name
	 * @param type
	 * @param head
	 */
	private void pass(String str, String name, String type, String head) {
		if(str == null) {
			return;
		}
		int i = 0;
		try {
			String[] s = str.split(" ");
			StringBuffer sb = new StringBuffer();
			int k = 0;
			for (i = 0; i < s.length; i++) {
				try {
					s[i] = df.format(Double.parseDouble(s[i]) * 
							PropertiesUtil.getConfig().getDouble("ice", 100));
				} catch (Exception e) {
				}
				sb.append(CommonUtil.countSpace(s[i].length())).append(s[i]);
				if(++k % 10 == 0 || (i + 1) % 288 == 0) {
					sb.append("\n");
					k = 0;
				}
				if((i + 1) % 41760 == 0) {
					int len = i / 41760;
					for (Map.Entry<String, HashSet<String>> entry : PropertiesUtil.getUserPath().entrySet()) {
						HashSet<String> set = entry.getValue();
						if(set.contains("all") || set.contains(type)) {
							pathOut = entry.getKey() + "/" + this.agency + "/" + this.time + "/";
							String path = pathOut + type + "/" + isobaric[len] + "/";
							FileUtil.creatPath(path);
							FileUtil.write(path + name, 
									String.format(head, isobaric[len], isobaric[len],
											PropertiesUtil.getConfig().getString(type + "." + isobaric[len])
											) + sb.toString(), false);
						}
					}
					sb.setLength(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	public void dopass() {
		try {
			File baseFile = new File(pathIn);
			File[] timeFiles = baseFile.listFiles();
			for (File timeFile : timeFiles) {
				dopass(timeFile.getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 处理单个文件
	 * @param timeFileName 时次预报文件名
	 * @return
	 */
	public boolean dopass(String timeFileName) {
		File timeFile = new File(pathIn + "/" + timeFileName);
		if(timeFile.exists()) {
			try {
				File[] dataFiles = timeFile.listFiles();
				String fileName = null;
				//找出基础数据
				for (File file : dataFiles) {
					fileName = file.getName();
					if(fileName.split(",").length == 1){
						GribBaseBean gb = new GribBaseBean(fileName, FileUtil.readFile(file));
						baseDataMap.put(gb.getName(), gb);
					}
				}
				
				//组装头信息
				String name = timeFile.getName();
				String n = time.substring(2, 4);
				String y = time.substring(4, 6);
				String r = time.substring(6, 8);
				String t = time.substring(8, 10);
				String yb = "0" + name.substring(name.length() - 2, name.length());
				String outName = n + y + r + t + "." + yb;
				String aveHead = "diamond 4 " + n + "年" + y + "月" + r + "日" + t + "点_" + agency + "_%shPa平均积冰" + yb + "小时预报\n" +
						"      " + n + " " + y + " " + r + " " + t + " " + yb + "    %s %s\n";
				String maxHead = "diamond 4 " + n + "年" + y + "月" + r + "日" + t + "点_" + agency + "_%shPa最大积冰" + yb + "小时预报\n" +
						"      " + n + " " + y + " " + r + " " + t + " " + yb + "    %s %s\n";
				//循环处理需要的文件
				for (File file : dataFiles) {
					fileName = file.getName();
					
					if(fileName.contains("Icing")){
						if(fileName.contains("Ave")) {
							//设置气压高度
							setIsobaric(fileName);
							//解析存储
							pass(FileUtil.readFile(file), outName, AVE_ICE, aveHead);
						} else if(fileName.contains("Max")) {
							//设置气压高度
							setIsobaric(fileName);
							//解析存储
							pass(FileUtil.readFile(file), outName, MAX_ICE, maxHead);
						}
					}
				}
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}
}
